﻿using Ecommerce.Common;
using Ecommerce.DTO;
using Ecommerce.tbCommodity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Uow;
using Newtonsoft.Json;
using Microsoft.Extensions.Caching.Distributed;
using Ecommerce.Application.Caching;

namespace Ecommerce
{
    public class OrderService : ApplicationService, IOrderInfoService
    {
        public IDistributedCache Cache { get; set; }
        private readonly IRepository<tbOrderInfo, Guid> _tbOrderInfos;
        private readonly IRepository<tbSaleNum, Guid> _tbSaleNums;
        private readonly IRepository<tbCommodityInfo, Guid> _tbCommodityInfos;
        public OrderService(IRepository<tbOrderInfo,Guid> tbOrderInfos,IRepository<tbSaleNum,Guid> tbSaleNums,IRepository<tbCommodityInfo,Guid> tbCommodityInfos)
        {
            _tbCommodityInfos = tbCommodityInfos;
            _tbOrderInfos = tbOrderInfos;
            _tbSaleNums = tbSaleNums;
        }

        /// <summary>
        /// 下订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public int AddOrder(CreateUpdatetbOrderInfoDto dto)
        {

            var obj = new tbOrderInfo()
            {
                OrderInfoTime = DateTime.Now,
                PayWayInfoId = dto.PayWayInfoId,
                MemberId = dto.MemberId,
                OrderInfoAddre = dto.OrderInfoAddre,
                OrderInfoName = dto.OrderInfoName,
                ShoppAddreTel = dto.ShoppAddreTel,
                OrderInfoSalePrice = dto.OrderInfoSalePrice,
                CommodCountPrice = dto.CommodCountPrice,
                OrderInfoBarCode = dto.OrderInfoBarCode,
                OrderInfoPayPrice = dto.OrderInfoPayPrice,
                OrderInfoActiveName = dto.OrderInfoActiveName,
                OrderDiscount = dto.OrderDiscount,
                OrderPrivilPrice = dto.OrderPrivilPrice,
                OrderInfoActivePrice = dto.OrderInfoActivePrice,
                OrderInvoiceM = dto.OrderInvoiceM,
                OrderWheShipments = dto.OrderWheShipments,
                OrderInfoAuditState = dto.OrderInfoAuditState,
                OrderInfoWhetherPay = dto.OrderInfoWhetherPay,
                OrderInfoState = dto.OrderInfoState,
                OrderInfoDeliveryState = dto.OrderInfoDeliveryState,
                OrderInfoWaybillNum = dto.OrderInfoWaybillNum,
                LogComId = dto.LogComId,
                CommodEvaluaGrade = dto.CommodEvaluaGrade,
                CommodEvaluaTime = dto.CommodEvaluaTime,
                CommodEvaluaOrder = dto.CommodEvaluaOrder
            };
            _tbOrderInfos.InsertAsync(obj);
            List<tbSaleNum> tbSales = new List<tbSaleNum>();
            //IdWorker idworker = new IdWorker(1);//雪花ID
            foreach (var item in dto.tbSaleNumDtos)
            {
                tbSales.Add(new tbSaleNum()
                {
                    OrderInfoId = obj.Id.ToString(),
                    CommodityId = item.Id.ToString(),
                    Num=item.Num,
                    Name=item.Name,
                    Price=item.Price,
                    SmallImage=item.SmallImage
                });

                var list = _tbCommodityInfos.Where(s => s.Id.ToString().Equals(item.Id.ToString())).FirstOrDefault();
                if(list.CommoidtyNum==0)
                {
                    return 2;
                }
                list.CommoidtyNum = list.CommoidtyNum - item.Num;
                _tbCommodityInfos.UpdateAsync(list);

            }
            _tbSaleNums.InsertManyAsync(tbSales);
            return 1;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpPost]
        [UnitOfWork]
        public int Cancellation(string guid)
        {

            var list = _tbOrderInfos.Where(o => o.Id.ToString().Equals(guid)).FirstOrDefault();//获取到该订单信息表的的信息
            list.OrderInfoAuditState = 20;//审核状态  20已取消
            list.OrderInfoState = 50;//订单状态    50取消订单
            var info = _tbSaleNums.Where(s => s.OrderInfoId.Equals(guid)).ToList();//查询到当前订单下面的商品信息
            foreach (var item in info)//进行循环
            {
                var commodity = _tbCommodityInfos.Where(s => s.Id.ToString().Equals(item.CommodityId)).FirstOrDefault();//通过订单表中的商品Id查询出该商品的信息
                commodity.CommoidtyNum = commodity.CommoidtyNum + item.Num;//将数量加上购买数量
                _tbCommodityInfos.UpdateAsync(commodity);//保存数据库
            }
            _tbOrderInfos.UpdateAsync(list);//保存数据库
            return 1;//返回1
        }

        /// <summary>
        /// 嵌套查询订单信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public  List<CreateUpdateOrderDisplayDto> ShowOrder(int options)
        {
            if(options==0)
            {
                var displays = (from info in _tbOrderInfos
                               select new CreateUpdateOrderDisplayDto
                               {
                                   OrderInfoTime = info.OrderInfoTime,//下单日期
                                   PayWayInfoId = info.PayWayInfoId,//支付方式
                                   MemberId = info.MemberId,//客户id
                                   OrderInfoId = info.Id.ToString(),//订单编号
                                   OrderInfoName = info.OrderInfoName,//收货人姓名
                                   ShoppAddreTel = info.ShoppAddreTel,//收货人电话
                                   OrderInfoSalePrice = info.OrderInfoSalePrice,//订单总金额
                                   OrderInfoBarCode = info.OrderInfoBarCode,//配送方式
                                   OrderWheShipments = info.OrderWheShipments,//是否发货
                                   OrderInfoAuditState = info.OrderInfoAuditState,//审核状态
                                   OrderInfoWhetherPay = info.OrderInfoWhetherPay,//是否支付
                                   OrderInfoState = info.OrderInfoState,//订单状态（已下单（未支付），待发货（已支付），已发货（待收货），已完成（已确认），订单取消（订单关闭））
                                   OrderInfoDeliveryState = info.OrderInfoDeliveryState,//配送状态
                                   CommodEvaluaOrder = info.CommodEvaluaOrder,//前台是否显示
                                   tbSaleNumDtos = (from infos in _tbOrderInfos
                                                    join num in _tbSaleNums
                                                    on info.Id.ToString() equals num.OrderInfoId
                                                    where infos.Id.ToString() == num.OrderInfoId
                                                    select new tbSaleNumDto
                                                    {
                                                        Name = num.Name,//商品名称
                                                        Num = num.Num,//商品数量
                                                        Price = num.Price,//商品价钱
                                                        SmallImage = num.SmallImage,//商品图片
                                                        CommodityId = num.CommodityId,//商品Id
                                                        OrderInfoId = num.OrderInfoId//订单编号
                                                    }).ToList()//订单子表
                               }).AsSingleQuery<CreateUpdateOrderDisplayDto>().ToList();
                return displays;
            }
            else
            {
                var display = (from info in _tbOrderInfos
                               where info.OrderInfoState.Equals(options)
                               select new CreateUpdateOrderDisplayDto
                               {
                                   OrderInfoTime = info.OrderInfoTime,//下单日期
                                   PayWayInfoId = info.PayWayInfoId,//支付方式
                                   MemberId = info.MemberId,//客户id
                                   OrderInfoId = info.Id.ToString(),//订单编号
                                   OrderInfoName = info.OrderInfoName,//收货人姓名
                                   ShoppAddreTel = info.ShoppAddreTel,//收货人电话
                                   OrderInfoSalePrice = info.OrderInfoSalePrice,//订单总金额
                                   OrderInfoBarCode = info.OrderInfoBarCode,//配送方式
                                   OrderWheShipments = info.OrderWheShipments,//是否发货
                                   OrderInfoAuditState = info.OrderInfoAuditState,//审核状态
                                   OrderInfoWhetherPay = info.OrderInfoWhetherPay,//是否支付
                                   OrderInfoState = info.OrderInfoState,//订单状态（已下单（未支付），待发货（已支付），已发货（待收货），已完成（已确认），订单取消（订单关闭））
                                   OrderInfoDeliveryState = info.OrderInfoDeliveryState,//配送状态
                                   CommodEvaluaOrder = info.CommodEvaluaOrder,//前台是否显示
                                   tbSaleNumDtos = (from infos in _tbOrderInfos
                                                    join num in _tbSaleNums
                                                    on info.Id.ToString() equals num.OrderInfoId
                                                    where infos.Id.ToString() == num.OrderInfoId
                                                    select new tbSaleNumDto
                                                    {
                                                        Name = num.Name,//商品名称
                                                        Num = num.Num,//商品数量
                                                        Price = num.Price,//商品价钱
                                                        SmallImage = num.SmallImage,//商品图片
                                                        CommodityId = num.CommodityId,//商品Id
                                                        OrderInfoId = num.OrderInfoId//订单编号
                                                    }).ToList()//订单子表
                               }).AsSingleQuery<CreateUpdateOrderDisplayDto>().ToList();
                return display;
            }
        }

        /// <summary>
        /// 物流
        /// </summary>
        /// <param name="ShipperCode"></param>
        /// <param name="LogisticCode"></param>
        /// <returns></returns>
        [HttpGet]
        public string GetSearchInfo(string ShipperCode, string LogisticCode)
        {
            ExpressdService kd = new ExpressdService();
            var json = kd.getOrderTracesByJson("YTO", "YT6007129269313");
            var Kdobj = JsonConvert.DeserializeObject<ExpressdDto>(json);
            return "";
        }

        /// <summary>
        /// Redis缓存显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<tbOrderInfoDto>> GettbOrderInfoDtos()
        {
            return await Cache.GetOrAddAsync("BookListByType",


                async () =>
                {
                    var list = _tbOrderInfos.ToList();
                    return ObjectMapper.Map<List<tbOrderInfo>, List<tbOrderInfoDto>>(list);
                },



            60
            );
            //TODO:后续如果有需要可以加缓存降级，即如果缓存中不存在主页楼层的数据，不去数据库中读，直接返回默认的楼层商品

        }

        [HttpGet]
        public async Task<List<tbOrderInfoDto>> GetOrderInfos()
        {
            var list = await _tbOrderInfos.ToListAsync();
            return ObjectMapper.Map<List<tbOrderInfo>, List<tbOrderInfoDto>>(list);
        }

    }
}
